<template>
  <div class="app-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef" size="small">
        <el-form-item label="支付编号">
          <el-input v-model="searchForm.paymentId" placeholder="请输入支付编号" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="患者姓名">
          <el-input v-model="searchForm.patientName" placeholder="请输入患者姓名" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="支付状态">
          <el-select v-model="searchForm.status" placeholder="请选择支付状态" clearable>
            <el-option label="待支付" value="待支付" />
            <el-option label="已支付" value="已支付" />
            <el-option label="已取消" value="已取消" />
            <el-option label="已退款" value="已退款" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select v-model="searchForm.paymentMethod" placeholder="请选择支付方式" clearable>
            <el-option label="现金" value="现金" />
            <el-option label="微信" value="微信" />
            <el-option label="支付宝" value="支付宝" />
            <el-option label="医保" value="医保" />
            <el-option label="银行卡" value="银行卡" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>支付记录列表</h3>
          <div>
            <el-button 
              type="primary" 
              @click="handleCreate" 
              v-permission="'payment:create'"
            >
              新增支付记录
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="paymentList"
        border
        style="width: 100%"
        row-key="id"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="paymentId" label="支付编号" min-width="180" />
        <el-table-column prop="patientName" label="患者姓名" min-width="120" />
        <el-table-column prop="amount" label="支付金额" min-width="120">
          <template #default="scope">
            {{ scope.row.amount.toFixed(2) }} 元
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" min-width="120" />
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" min-width="180" sortable="custom">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="paidAt" label="支付时间" min-width="180">
          <template #default="scope">
            {{ scope.row.paidAt ? formatDateTime(scope.row.paidAt) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="220">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleDetail(scope.row)"
              v-permission="'payment:read'"
            >
              详情
            </el-button>
            <el-button
              type="success"
              link
              size="small"
              @click="handleProcess(scope.row)"
              v-if="scope.row.status === '待支付'"
              v-permission="'payment:update'"
            >
              处理支付
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleCancel(scope.row)"
              v-if="scope.row.status === '待支付'"
              v-permission="'payment:delete'"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="page"
          v-model:page-size="limit"
          @size-change="fetchPayments"
          @current-change="fetchPayments"
        />
      </div>
    </el-card>

    <!-- 处理支付弹窗 -->
    <el-dialog
      title="处理支付"
      v-model="processDialog.visible"
      width="500px"
    >
      <el-form :model="processDialog.form" label-width="120px" ref="processFormRef">
        <el-form-item label="支付状态" prop="status">
          <el-select v-model="processDialog.form.status" placeholder="请选择支付状态" style="width: 100%">
            <el-option label="成功" value="成功" />
            <el-option label="失败" value="失败" />
          </el-select>
        </el-form-item>
        <el-form-item label="交易流水号" prop="transactionId">
          <el-input v-model="processDialog.form.transactionId" placeholder="请输入交易流水号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="processDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmProcess" :loading="processDialog.loading">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { paymentAPI } from '@/utils/api'
import { formatDateTime } from '@/utils/format'

const router = useRouter()

// 数据列表
const paymentList = ref([])
const loading = ref(false)
const total = ref(0)
const page = ref(1)
const limit = ref(20)
const sortBy = ref('createdAt')
const order = ref('desc')

// 搜索表单
const searchFormRef = ref(null)
const searchForm = reactive({
  paymentId: '',
  patientName: '',
  status: '',
  paymentMethod: ''
})

// 处理支付对话框
const processDialog = reactive({
  visible: false,
  loading: false,
  form: {
    paymentId: '',
    status: '成功',
    transactionId: ''
  }
})

// 获取支付记录列表
const fetchPayments = async () => {
  loading.value = true
  try {
    const params = {
      page: page.value,
      limit: limit.value,
      sortBy: sortBy.value,
      order: order.value,
      ...searchForm
    }
    
    const res = await paymentAPI.getPayments(params)
    console.log('支付API响应:', res) // 添加日志查看实际响应结构
    
    // 根据响应格式获取数据
    paymentList.value = res.data.payments || []
    total.value = res.data.total || 0
    
  } catch (error) {
    console.error('获取支付记录失败', error)
    console.log('错误详情:', error.message, error.response || error)
    // 拦截器已经显示错误消息，这里不需要重复显示
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  fetchPayments()
}

// 重置搜索
const resetSearch = () => {
  searchFormRef.value.resetFields()
  page.value = 1
  fetchPayments()
}

// 排序变化
const handleSortChange = (column) => {
  if (column.prop) {
    sortBy.value = column.prop
    order.value = column.order === 'ascending' ? 'asc' : 'desc'
    fetchPayments()
  }
}

// 新增支付记录
const handleCreate = () => {
  router.push('/payments/create')
}

// 查看详情
const handleDetail = (row) => {
  router.push(`/payments/detail/${row.id}`)
}

// 处理支付
const handleProcess = (row) => {
  processDialog.form.paymentId = row.id
  processDialog.form.status = '成功'
  processDialog.form.transactionId = ''
  processDialog.visible = true
}

// 确认处理支付
const confirmProcess = async () => {
  processDialog.loading = true
  try {
    const res = await paymentAPI.processPayment(
      processDialog.form.paymentId,
      {
        status: processDialog.form.status,
        transactionId: processDialog.form.transactionId
      }
    )
    
    if (res.data && res.data.success) {
      ElMessage.success('支付处理成功')
      processDialog.visible = false
      fetchPayments()
    } else {
      ElMessage.error(res.data.message || '支付处理失败')
    }
  } catch (error) {
    console.error('支付处理失败', error)
    ElMessage.error('支付处理失败')
  } finally {
    processDialog.loading = false
  }
}

// 取消支付
const handleCancel = (row) => {
  ElMessageBox.confirm('确定要取消此支付记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await paymentAPI.cancelPayment(row.id)
      if (res.data && res.data.success) {
        ElMessage.success('支付已取消')
        fetchPayments()
      } else {
        ElMessage.error(res.data.message || '取消支付失败')
      }
    } catch (error) {
      console.error('取消支付失败', error)
      ElMessage.error('取消支付失败')
    }
  }).catch(() => {})
}

// 获取状态标签类型
const getStatusType = (status) => {
  const map = {
    '待支付': 'warning',
    '已支付': 'success',
    '成功': 'success',
    '已取消': 'info',
    '已退款': 'danger'
  }
  return map[status] || 'info'
}

// 生命周期钩子
onMounted(() => {
  fetchPayments()
})
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 